<?php

// sleep(8);
// Notificar todos los errores excepto E_NOTICE
// Este es el valor predeterminado establecido en php.ini
error_reporting(E_ALL ^ E_NOTICE);
// session_start();

//ini_set ('error_reporting', E_ALL ^ E_NOTICE ^ E_WARNING );

// Desactivar toda notificaci�n de error
//error_reporting(0);

//ini_set('memory_limit', '-1');
set_time_limit(1000);
ini_set("memory_limit", "128M"); //ojo

// asd //si hay un error lo larga rapido rck
// sleep(1);

/* esto hace tardar el pedido ajax rck*/
include "../include/config.php";
// include "../include/db.php"; //rck hace que tarde!! ojo!!


$gaSql['user'] = DB_USER;
$gaSql['password'] = DB_PASS;
$gaSql['db'] = DB_NAME;
$gaSql['server'] = DB_HOST;

if (!$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password'])) {
    fatal_error('Could not open connection to server');
}

if (!mysql_select_db($gaSql['db'], $gaSql['link'])) {
    fatal_error('Could not select database ');
}



//include("include/db.php");

//$query = mysql_real_escape_string($_REQUEST['query']);
$query = $_REQUEST['query'];

//

$query  = str_replace("\\'", "'", $query );
$query  = str_replace("\\\"", "'", $query );

//echo $query; 

//print_r($_REQUEST);
//die();

if (stristr($query, 'insert')) {
    //$query = utf8_decode($query);
    $query = urldecode($query);
    $query = utf8_decode($query);
}

$result = mysql_query($query) or trigger_error(mysql_error());


$jsonArr = array();
$arrTodo = array();

//try {
//    $result = mysql_query($query);
//} catch (Exception $e) {
//
//    $jsonArr['errorMsj'] = $e->getMessage();
//    $jsonArr['status'] = "error";
//    
//    echo json_encode($jsonArr);
//    die();
//}

$jsonArr['query'] = $query; //solo para probar RCK

function filtrar($var){
    
    //$k => $v
    return $var;
}
//array_filter($array1, "")
        

if (stristr($query, 'insert')) {
    $jsonArr['insert_id'] = mysql_insert_id();
}

if (stristr($query, 'select')) {
//if (mysql_num_rows($result) > 0) {

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {//solo las claves
        $row = array_map("utf8_encode", $row);        
        $arrTodo[] = $row;
    }
    
//    while ($row = mysql_fetch_object($result)) {
//        //$row = array_map("utf8_encode", $row);        
//        $arrTodo[] = $row;
//    }

    $jsonArr['total'] = mysql_num_rows($result);
    $jsonArr['objetos'] = $arrTodo;
} else {
    $jsonArr['msj'] = "ejecutado con exito";
}


$jsonArr['status'] = "ok";

//$b = array("uno", "dos", "tres", "cuatro", "cinco");
//$b = array_map("utf8_encode", $b);

//$jsonArr = array_map("utf8_encode", $jsonArr);

echo json_encode($jsonArr);

// echo "holas";

?>